<template>
  <van-field
    :label="titleText(options, item)"
    :name="item.itemTitle"
    :required="item.isRequired === 'Y'"
    :rules="[
      { required: item.isRequired === 'Y', message: '请上传' + item.itemTitle },
    ]"
    label-width="33rem"
  >
    <template #input>
      <p v-if="options.showDesc" class="desc f12 mb10">
        {{ options.description }}
      </p>
      <van-uploader
        v-model="fileList"
        :after-read="afterRead"
        :before-delete="beforeDelete"
        :before-read="beforeRead"
        :deletable="type !== 'view'"
        :disabled="type === 'view'"
        :max-count="options.limit || 1"
        :name="item.remark"
        preview-size="8rem"
      >
      </van-uploader>
    </template>
  </van-field>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import Compressor from "compressorjs";
import { ref } from "vue";

//defineOptions({ name: "H5PictureUpload" });

const { item } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);

const fileList = ref(item.value);
// const fileSize = ref(5)
const { options } = JSON.parse(item.vformJson);
// 传递值改变后
const onChange = () => emits("change", item);
// 此时可以自行将文件上传至服务器
const afterRead = () => {
  item.value = fileList.value;
  onChange();
};
// 文件大小不能超过
// const onOversize = (file) => {
//   showToast('文件大小不能超过 ' + fileSize.value + 'M');
// };
// 部分手机在拍照上传时会出现图片被旋转 90 度的问题
// compressor.js 默认开启 checkOrientation 选项
// 会将图片修正为正确方向
const beforeRead = (file) => {
  return new Promise((resolve) => {
    new Compressor(file, {
      success: resolve(file),
      error(err) {
        console.log(err.message);
      },
    });
  });
};
// 删除
const beforeDelete = (file, n) => {
  fileList.value.splice(n.index, 1);
  afterRead();
};
</script>